package com.medica.ledproject.socke;

/**
 * @author xiaona
 * @date 2024/5/30
 * @description TODO
 */

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class SocketServer
{
    private static final Logger log = LoggerFactory.getLogger(SocketServer.class);

    @Resource
    private SocketInitializer socketInitializer;
    private ServerBootstrap serverBootstrap;

    @Value("${netty.port:8902}")
    private int port;

    @Value("${netty.bossThread:1}")
    private int bossThread;

    public void start()
    {
        init();
        this.serverBootstrap.bind(this.port);
        log.info("Netty started on port: {} (TCP) with boss thread {}", Integer.valueOf(this.port), Integer.valueOf(this.bossThread));
    }

    private void init()
    {
        NioEventLoopGroup bossGroup = new NioEventLoopGroup(this.bossThread);

        NioEventLoopGroup workerGroup = new NioEventLoopGroup();
        this.serverBootstrap = new ServerBootstrap();

        ((ServerBootstrap)this.serverBootstrap.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class))
                .childHandler(this.socketInitializer);
    }

    public ServerBootstrap getServerBootstrap()
    {
        return this.serverBootstrap;
    }
}